package cc.lucien.repository.impl;

import cc.lucien.entity.User;
import cc.lucien.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author lucien-ma
 * @date 2021/9/13
 * @apiNote
 */
@Repository
public class UserRepositoryImpl implements UserRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<User> findAll() {
        return jdbcTemplate.query(
                "select * from users",
                new BeanPropertyRowMapper<>(User.class)
        );
    }

    @Override
    public User findById(Integer id) {
        return jdbcTemplate.queryForObject(
                "select * from users where id = ?",
                new BeanPropertyRowMapper<>(User.class),
                id
        );
    }

    @Override
    public int save(User user) {
        return jdbcTemplate.update(
                "insert into users(id,username,password) values(?,?,?)",
                user.getId(),
                user.getUsername(),
                user.getPassword()
        );
    }

    @Override
    public int update(User user) {
        return jdbcTemplate.update(
                "update users set username=?,password=? where id=?",
                user.getUsername(),
                user.getPassword(),
                user.getId()
        );
    }

    @Override
    public int deleteById(Integer id) {
        return jdbcTemplate.update(
                "delete from users where id=?",
                id
        );
    }
}
